package com.sitech.ismp.common.server;

import org.springframework.beans.factory.BeanFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public final class SpringContext {
    private static BeanFactory springBeanFactory = null;
    private static final Lock lock = new ReentrantLock();
    private static final Condition beanFactoryReady = lock.newCondition();

    public SpringContext() {
    }

    public static Object getBean(String beanName) throws Exception {
        if (springBeanFactory == null) {
            lock.lock();
            try {
                beanFactoryReady.await(60, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new Exception("没有初始化BeanFactory！", e);
            } finally {
                lock.unlock();
            }
        }
        return springBeanFactory.getBean(beanName);
    }

    public static void setBeanFactory(BeanFactory beanFactory) {
        lock.lock();
        try {
            springBeanFactory = beanFactory;
            beanFactoryReady.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
